﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace BridgeWebSystemLib.Core.Util
{
    public class LogUtil
    {
        private static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "WebLog";

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="fileName"></param>
        /// <param name="text"></param>
        public static void WriteLog(string directory, string fileName, string text)
        {
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
                Thread.Sleep(1000);
            }
            try
            {
                string sFileName = directory + "//" + fileName + "{0}.log";
                string sLogFileName = null;
                for (int i = 0; true; i++)
                {
                    if (i == 0)
                    {
                        sLogFileName = string.Format(sFileName, "");
                    }
                    if (i != 0)
                    {
                        sLogFileName = string.Format(sFileName, i.ToString());//如果文件名被占用，建立strFileName（index）文件
                    }
                    System.IO.FileInfo f = new System.IO.FileInfo(sLogFileName);
                    if (f == null || !f.Exists)
                    {
                        System.IO.File.Create(sLogFileName).Close();//没有文件，创建文件
                        break;
                    }
                    else if (f.Length > 50000000L)//文件不能太长
                    {
                        continue;//进入下次循环，从新建立文件
                    }
                    else
                    {
                        break;//文件存在
                    }
                }
            
                System.IO.StreamWriter w = new System.IO.StreamWriter(sLogFileName, true);
                w.WriteLine();
                w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                w.WriteLine(text);
                w.Flush();
                w.Close();
            }
            catch { };
        }

        public static void WriteLog(string text)
        {
            DateTime dtCurrent = DateTime.Now;
            WriteLog(logPath, dtCurrent.ToString("yyyy-MM-dd"), text);
        }

        public static void WriteLog(string directory, string text)
        {
            DateTime dtCurrent = DateTime.Now;
            WriteLog(directory, dtCurrent.ToString("yyyy-MM-dd"), text);
        }
    }
}
